import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/other/image_upload_result_entity.dart';
import 'package:ball_lion/entity/other/user_info_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/server/http/dio_utils.dart';
import 'package:ball_lion/utils/image_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/mine/widgets/list_cell_box.dart';
import 'package:ball_lion/widgets/select_bottomsheet.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class MyEditInfoPage extends StatefulWidget {
  const MyEditInfoPage({super.key});

  @override
  State<MyEditInfoPage> createState() => _MyEditInfoPageState();
}

class _MyEditInfoPageState extends State<MyEditInfoPage> {
  tapEditAvartar() async {
    await User.fetchUserInfo();
    Utils.onEvent('wode_pd_xgnc', params: {'wode_pd_xgnc': '1'});
    if (User.info!.avatarUpdateDays! > 0) {
      Toast.text('${User.info!.avatarUpdateDays!}日后可以修改头像');
      return;
    }
    final r = await Get.bottomSheet(const SelectBottomSheet(["拍照", "从手机相册选择"]));
    String? path;
    if (r == 0) {
      final file = await ImageUtils.pickPhotoFromCamera();
      path = file?.path;
    } else if (r == 1) {
      final files = await ImageUtils.pickPhotoFromGallery();
      if (files != null) {
        File? file = await files.first.file;
        path = file?.path;
      }
    } else if (r == 2) {
      await Get.toNamed(Routes.systemAvatars);
      await User.fetchUserInfo(fetchFocus: false);
      getEditState();
      update();
    } else {
      return;
    }
    if (path == null) {
      return;
    }
    final croppedFile = await ImageUtils.cropImage(path);
    if (croppedFile == null) {
      return;
    }
    List<ImageUploadResultEntity>? result =
        await DioUtils.uploadImage([croppedFile], 'avatar');
    if (result != null) {
      int? code =
          await UserApi.avatarUpdate(result.first.url!, showLoading: true);
      if (code != null && code == 200) {
        // Toast.text('修改头像成功!')
        await User.fetchUserInfo(fetchFocus: false);
        getEditState();
        update();
      }
    }
  }

  tapEditName() {
    Utils.onEvent('wode_pd_xgnc', params: {'wode_pd_xgnc': '0'});
    Get.toNamed(Routes.myEditName)?.then((value) {
      getEditState();
      update();
    });
  }

  tapInviter() {
    if (User.info?.channelPromotion == null && User.info?.channelAddDays != 0) {
      Get.toNamed(Routes.myInviter, arguments: 1);
    }
  }

  tapEditDesc() => Get.toNamed(Routes.myEditDesc)?.then((value) => update());

  String get name => userEditState?.name ?? User.info?.name ?? "";
  String get sign => "";

  UserEditStateEntity? userEditState;

  @override
  void initState() {
    getEditState();
    super.initState();
  }

  Future getEditState() async {
    userEditState = await UserApi.getUserEditState();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.scaffoldBg,
      appBar: Styles.appBar(
          title: const QsText("编辑资料"), backgroundColor: Colours.transparent),
      body: SingleChildScrollView(
        child: Column(
          children: [
            header(),
            ListCellBox(children: [
              cell("用户昵称",
                      right: name, showAudit: userEditState?.nameStatus == 0)
                  .tap(tapEditName),
              const Divider(
                height: 0.5,
                indent: 12,
                endIndent: 20,
                color: Colours.greyEE,
              ),
            ]).marginSymmetric(horizontal: 8)
          ],
        ),
      ),
    );
  }

  Widget header() => Container(
        width: double.infinity,
        margin: const EdgeInsets.all(8),
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
            color: Colours.white, borderRadius: BorderRadius.circular(8)),
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(height: 32),
            Container(
              width: 80,
              height: 80,
              clipBehavior: Clip.antiAlias,
              decoration: const BoxDecoration(shape: BoxShape.circle),
              child: CachedNetworkImage(
                  imageUrl: userEditState?.avatar ?? User.info?.avatar ?? ""),
            ),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
              child: const QsText("点击更换头像"),
            ),
            if (userEditState?.avatarStatus == 0)
              const QsText("（审核中）", fontSize: 12, color: Colours.R5)
                  .paddingOnly(top: 2)
            else
              Container(height: 18),
            Container(height: 15)
          ],
        ).tap(tapEditAvartar),
      );

  Widget cell(String text,
          {String right = "", bool showArrow = true, bool showAudit = false}) =>
      Container(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        height: 46,
        child: Row(
          children: [
            QsText(text, fontSize: 14, color: Colours.N9),
            // const Spacer(),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  if (showAudit)
                    const QsText("（审核中）", fontSize: 12, color: Colours.R5),
                  Flexible(
                    child: QsText(right,
                            textAlign: TextAlign.right,
                            maxLines: 2,
                            fontSize: 14,
                            color: Colours.N8)
                        .marginSymmetric(horizontal: 8),
                  ),
                ],
              ),
            ),
            Image.asset(Utils.getImgPath("icon_arrow_right.png"),
                width: 6, height: 10)
          ],
        ),
      );

  String getInviteText() {
    String? text = User.info?.channelPromotion;
    if (text == null) {
      if (User.info?.channelAddDays == 0) {
        text = '绑定邀请人时间已过';
      } else {
        text = '您还有${User.info?.channelAddDays}天可绑定邀请人';
      }
    }
    return text;
  }
}
